package com.mayuhao.homework.chapter3.homework3四2_自定义对话框;

import androidx.activity.ComponentActivity;
import androidx.activity.OnBackPressedDispatcher;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.mayuhao.homework.R;

public class CustomDialogActivity extends AppCompatActivity {
    //返回键
    private final OnBackPressedDispatcher mOnBackPressedDispatcher =
            new OnBackPressedDispatcher(new Runnable() {
                @Override
                public void run() {
                    // Calling onBackPressed() on an Activity with its state saved can cause an
                    // error on devices on API levels before 26. We catch that specific error and
                    // throw all others.
                    try {
                        CustomDialogActivity.super.onBackPressed();
                    } catch (IllegalStateException e) {
                        if (!TextUtils.equals(e.getMessage(),
                                "Can not perform this action after onSaveInstanceState")) {
                            throw e;
                        }
                    }
                }
            });

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_custom_dialog);
    }

    @Override
    public void onBackPressed() {
        CommonDialog commonDialog = new CommonDialog(CustomDialogActivity.this);
        commonDialog.setTitle("提示").setMessage("确定要退出应用程序吗？")
                .setCancel("取消", new CommonDialog.MyCancelListener() {
                    @Override
                    public void onCancel(CommonDialog dialog) {
                        Toast.makeText(CustomDialogActivity.this,"已取消", Toast.LENGTH_SHORT).show();
                    }
                }).setConfirm("确定", new CommonDialog.MyConfirmListener() {
            @Override
            public void onConfirm(CommonDialog dialog) {
                mOnBackPressedDispatcher.onBackPressed();  //super.onBackPressed();查源码取而代之
                Toast.makeText(CustomDialogActivity.this,"已退出", Toast.LENGTH_LONG).show();
            }
        }).show();
    }
}